package b1.mobile.blackberry.dao;

import java.util.Vector;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import b1.mobile.blackberry.controller.AgentController;
import b1.mobile.blackberry.entity.BusinessPartnerEntity;
import b1.mobile.blackberry.io.http.ResponseParserHelper;
import b1.mobile.blackberry.io.http.Serviceworker;
import b1.mobile.blackberry.io.http.SoapContentProvider;

public class BusinessPartnerDAO extends CommonDAO {
	public static String OP_LIST = "GetBPListJSON";
	public static String OP_TOTAL = "GetBPCount";
	
	
	public BusinessPartnerDAO(DataAccessDelegate delegate) {
		super(delegate);
	}

	public void onGetResult(Serviceworker worker) {
		super.onGetResult(worker);
		if(worker.responseCode == 200){
			if(worker.getOperator().equals(OP_LIST)){
				parseList(worker);
			} else if(worker.getOperator().equals(OP_TOTAL)){
				parseTotal(worker);
			}
		} 
	}

	public void list(String keyword, int pageIndex, int pageSize){
		String[] names = new String[]{"Keyword", "PageIndex", "PageSize"};
		String[] values = new String[] {keyword, String.valueOf(pageIndex), String.valueOf(pageSize)};
		SoapContentProvider soap = new SoapContentProvider(OP_LIST, names, values);
		
		try{
			Serviceworker worker = new Serviceworker(this, AgentController.getServer(), soap);
			(new Thread(worker)).start();
		} catch (Exception ex){
			
		}
	}
	
	protected void parseList(Serviceworker worker){
		ResponseParserHelper help = new ResponseParserHelper(worker.responseMessage);
		JSONArray array = (JSONArray)help.parse("GetBPListJSONResult");
		
		Vector items = new Vector();
		for(int i = 0; i < array.length(); i++){
			try {
				JSONObject json = array.getJSONObject(i);
				BusinessPartnerEntity ety = new BusinessPartnerEntity(json);
				items.addElement(ety);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		_delegate.onDataReady(worker, items);
	}
	
	public void getTotal(String keyword){
		String[] names = new String[]{"Keyword"};
		String[] values = new String[] {keyword};
		SoapContentProvider soap = new SoapContentProvider(OP_TOTAL, names, values);
		
		try{
			Serviceworker worker = new Serviceworker(this, AgentController.getServer(), soap);
			(new Thread(worker)).start();
		} catch (Exception ex){
			
		}
	}
	
	protected void parseTotal(Serviceworker worker) {
		ResponseParserHelper help = new ResponseParserHelper(worker.responseMessage);
		String countStr = (String)help.parse("GetBPCountResult");		
		_delegate.onDataReady(worker, new Integer(Integer.parseInt(countStr)));
	}

}
